package util;

import exception.EncodingErrorException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author Miss Chen
 * @version 1.0
 * @date 2024年09月03日14:54
 */
public class CookieUtil {
    public static void addCookie(String name, String value, HttpServletResponse response){

        try {
            Cookie cookie=new Cookie(name, URLEncoder.encode(value,"UTF-8"));
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    public static void addCookie(String name, String value,int maxAge, HttpServletResponse response){
        try {
            Cookie cookie=new Cookie(name, URLEncoder.encode(value,"UTF-8"));
            cookie.setMaxAge(maxAge);
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    public static void deleteCookie(String name,HttpServletResponse response){
        addCookie(name,"",0,response);
    }
    public static void modifyCookie(String name, String value, HttpServletResponse response){
        addCookie(name,value,response);
    }
    public static void modifyCookie(String name, String value,int maxAge, HttpServletResponse response){
        addCookie(name,value,maxAge,response);
    }
    public static String findByName(String name, HttpServletRequest request){
        Cookie[] cookies=request.getCookies();


        try {
            if(null!=cookies){
                for(Cookie cookie:cookies){
                    if(cookie.getName().equals(name)){
                        return URLDecoder.decode(cookie.getValue(),"UTF-8");
                    }
                }
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new EncodingErrorException("字符集有误");
        }

        return null;

    }

}
